package com.yu.yupicture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.yupicture.Untils.ColorSimilarUtils;
import com.yu.yupicture.api.aliyunApi.model.ImageEditRequest;
import com.yu.yupicture.api.aliyunApi.model.ImageEditResponse;
import com.yu.yupicture.api.aliyunApi.sub.aliImageEditRequestApi;
import com.yu.yupicture.manger.upload.FileUntil;
import com.yu.yupicture.Untils.ThrowUntil;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import com.yu.yupicture.manger.upload.CommenUpliadUntil;
import com.yu.yupicture.manger.upload.urlUntil;
import com.yu.yupicture.mapper.PictureMapper;
import com.yu.yupicture.model.domain.dto.picture.*;
import com.yu.yupicture.model.domain.entry.Picture;
import com.yu.yupicture.model.domain.entry.Space;
import com.yu.yupicture.model.domain.entry.User;
import com.yu.yupicture.model.domain.vo.PictureVO;
import com.yu.yupicture.model.domain.vo.UserVo;
import com.yu.yupicture.model.enums.PictureReviewStatusEnum;
import com.yu.yupicture.model.enums.UserRoleEnums;
import com.yu.yupicture.service.PictureService;
import com.yu.yupicture.service.SpaceService;
import com.yu.yupicture.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author Li Shuokang
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-07-30 15:32:13
 */
@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private FileUntil fileUntil;
    @Resource
    private UserService userService;
    @Resource
    private urlUntil urlUntil;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;

//    @Resource
//    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private aliImageEditRequestApi aliImageEditRequestApi;


    /**
     * 上传文件
     *
     * @param user
     * @param input
     * @return
     */
    @Override
    public PictureVO uploadPicture(User user, PictureUploadRequest pictureUploadRequest, Object input) {
        //校验参数
        if (user == null || input == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR);
        }
        //校验空间
        Long spaceId=null;
        spaceId = pictureUploadRequest.getSpaceId();
        Space oldSpace=null;
        //校验是否超过了个人空间的容量
        if (spaceId!=null){
            oldSpace = spaceService.getById(spaceId);
            ThrowUntil.throwIf(oldSpace==null,ErrorCode.NOT_FOUND_ERROR,"空间不存在");

            //校验权限
            ThrowUntil.throwIf(!oldSpace.getUserId().equals(user.getId()),ErrorCode.NO_AUTH_ERROR,"您没有权限操作该空间");
            if (oldSpace.getMaxCount()<=oldSpace.getTotalCount()){
                throw new biusnessException(ErrorCode.NO_AUTH_ERROR,"空间已满");
            }
            if (oldSpace.getMaxSize()<=oldSpace.getTotalSize()){
                throw new biusnessException(ErrorCode.NO_AUTH_ERROR,"空间已满");
            }
        }

        Long pictureId = null;
        //1：判断是新增，还是更新
        if (pictureUploadRequest.getId() != null) {
            pictureId = pictureUploadRequest.getId();
        }
        //2:如果是更新，需要先查询数据库，判断图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            if (oldPicture == null) {
                throw new biusnessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            }
            //判断该用户是否有权限修改
            if (!isAdmin(user) && !oldPicture.getUserId().equals(user.getId())) {
                throw new biusnessException(ErrorCode.NO_AUTH_ERROR, "您没有权限修改该图片");
            }
            //不能修改空间id
            if (pictureUploadRequest.getSpaceId() != null && !pictureUploadRequest.getSpaceId().equals(oldPicture.getSpaceId())) {
                throw new biusnessException(ErrorCode.NO_AUTH_ERROR, "不能修改图片空间");
            }
        }
        String pathPrev;
        pathPrev= "public" + "/" + user.getId() + "/";

        //设置私有空间路径
        if (spaceId!=null){
            pathPrev="private"+oldSpace.getId()+"/";
        }

        CommenUpliadUntil commenUpliadUntil = fileUntil;
        if (input instanceof String) {
            commenUpliadUntil = urlUntil;
        }
        //3：上传文件
        UploadPictureResult uploadPictureResult = commenUpliadUntil.uploadFile(pathPrev, input);
        //4：写入数据库
        Picture picture = new Picture();
        //1：设置审核参数
        this.addReviewParams(picture, user);

        picture.setUserId(user.getId());
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest.getPicName() != null) {
            picName = pictureUploadRequest.getPicName();
        }

        //2：设置空间id
        picture.setSpaceId(spaceId);

        picture.setCategory(pictureUploadRequest.getCategory());
        picture.setTags(JSONUtil.toJsonStr(pictureUploadRequest.getTagList()));

        picture.setName(picName);
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUrl(uploadPictureResult.getUrl());
        //2：设置缩略图
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setPicSize(uploadPictureResult.getPicSize());
        //设置图片主色调
        picture.setPicColor(uploadPictureResult.getPicColor());

        if (pictureId != null) {
            picture.setEditTime(new Date());
            picture.setId(pictureId);
        }

        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean b = this.saveOrUpdate(picture);
            ThrowUntil.throwIf(!b, ErrorCode.OPERATION_ERROR, "图片上传失败");
            //修改空间的总数量和总大小
            if (finalSpaceId !=null){
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalCount=totalCount+1,totalSize=totalSize+" + uploadPictureResult.getPicSize())
                        .update();
                ThrowUntil.throwIf(!update, ErrorCode.OPERATION_ERROR, "空间更新失败");
            }
            return b;
        });

        //5：返回结果
        return PictureVO.objToVo(picture);
    }


    /**
     * 判断是否为管理员
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && user.getUserRole().equals(UserRoleEnums.ADMIN.getValue());
    }


    /**
     * 获取查询条件 类
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        if (pictureQueryRequest == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        Long spaceId = pictureQueryRequest.getSpaceId();
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Date reviewTime = pictureQueryRequest.getReviewTime();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();

        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();


        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(searchText)) {
            queryWrapper.and(
                    qw ->
                            qw.like("name", searchText)
                                    .or().
                                    like("introduction", searchText));
        }

        // 空间id是否为空
        queryWrapper.eq(ObjUtil.isNotNull(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(pictureQueryRequest.getNullSpaceId(), "spaceId");

        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        //只查询没有被删除的 图片
        queryWrapper.eq("isDelete", 0);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotNull(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotNull(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotNull(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotNull(picScale), "picScale", picScale);
        queryWrapper.eq(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(ObjUtil.isNotNull(userId), "userId", userId);
        queryWrapper.like(ObjUtil.isNotNull(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotNull(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotNull(reviewTime), "reviewTime", reviewTime);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        queryWrapper.gt(ObjUtil.isNotNull(startEditTime), "startEditTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotNull(endEditTime), "endEditTime", endEditTime);

        // 只展示审核通过的图片
        queryWrapper.eq(ObjUtil.isNotNull(reviewStatus), "reviewStatus", reviewStatus);


        if (tags != null && !tags.isEmpty()) {
            for (String tag : tags) {
                queryWrapper.like(StrUtil.isNotBlank(tag), "tags", "\"" + tag + "\"");
            }
        }
        return queryWrapper;
    }

    /**
     * 分页查询（管理端）
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public Page<Picture> page(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = this.getQueryWrapper(pictureQueryRequest);
        int pageSize = pictureQueryRequest.getPageSize();
        int current = pictureQueryRequest.getCurrent();
        return this.page(new Page<>(current, pageSize), queryWrapper);
    }

    /**
     * 分页查询（用户端）
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public Page<PictureVO> pageVo(PictureQueryRequest pictureQueryRequest, User user) {
        // 只查询审核通过的图片
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        //
        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null){
            pictureQueryRequest.setNullSpaceId(true);
        }

        QueryWrapper<Picture> queryWrapper = this.getQueryWrapper(pictureQueryRequest);
        int pageSize = pictureQueryRequest.getPageSize();
        int current = pictureQueryRequest.getCurrent();
        Page<Picture> page = this.page(new Page<>(current, pageSize), queryWrapper);

        // 获取当前页数据
        List<Picture> pictureList = page.getRecords();
        //判断数据是否为空
        if (pictureList.isEmpty()) {
            return new Page<>(0, 0);
        }
        //脱敏
        List<PictureVO> pictureVOList = this.getPictureVOList(pictureList);
        //返回结果
        Page<PictureVO> voPage = new Page<>(current, pageSize, page.getTotal());
        voPage.setRecords(pictureVOList);
        return voPage;
    }

    /**
     * 图片集合进行脱敏
     *
     * @param pictureList
     * @return
     */
    @Override
    public List<PictureVO> getPictureVOList(List<Picture> pictureList) {
        if (CollUtil.isEmpty(pictureList)) {
            return List.of();
        }
        List<PictureVO> pictureVOList = pictureList.stream().map(pic -> {
            PictureVO pictureVO = PictureVO.objToVo(pic);
            pictureVO.setTags(JSONUtil.parseArray(pic.getTags()).stream().map(Object::toString).toList());
            return pictureVO;
        }).toList();
        //获取用户id
        Set<Long> userIds = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, UserVo> userVoMap = userIds.stream().map(
                userId -> {
                    User u = userService.getById(userId);
                    if (u == null) {
                        log.error("分页查询-用户端 user not found,userId:{}", userId);
                    }
                    //脱敏
                    return userService.getUserVo(u);
                }
        ).collect(Collectors.toMap(UserVo::getId, userVo -> userVo));

        //填充用户信息
        return pictureVOList.stream()
                .peek(picVo -> picVo.setUser(userVoMap.get(picVo.getUserId()))).toList();
    }

    /**
     * 将单个图片转vo
     *
     * @param picture
     * @return
     */
    @Override
    public PictureVO getPicVoByPicture(Picture picture) {
        ThrowUntil.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 设置用户信息
        User u = userService.getById(picture.getUserId());
        if (u != null) {
            pictureVO.setUser(userService.getUserVo(u));
        } else {
            log.error("将单个图片转vo 用户不存在");
        }

        return pictureVO;
    }

    /**
     * 根据id查询图片 picture
     *
     * @param id
     * @return
     */
    @Override
    public Picture getPictureById(Long id) {
        ThrowUntil.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        Picture picture = this.baseMapper.selectById(id);
        if (picture == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "图片不存在");
        }
        return picture;
    }

    //根据id查询图片 pictureVo
    @Override
    public PictureVO getPictureVoById(Long id,User user) {
        ThrowUntil.throwIf(id == null||user==null, ErrorCode.PARAMS_ERROR);
        Picture picture = this.baseMapper.selectById(id);
        if (picture == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "图片不存在");
        }
        Long spaceId = picture.getSpaceId();
        if (spaceId != null){
            Space space = spaceService.getSpaceById(spaceId);
           if (!Objects.equals(space.getUserId(), user.getId())){
               throw  new biusnessException(ErrorCode.NO_AUTH_ERROR, "无权限操作此空间图片");
           }
        }
        return this.getPicVoByPicture(picture);
    }

    /**
     * 根据id删除图片 -管理员
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(Long id) {
        ThrowUntil.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        Picture picture = this.getPictureById(id);
        if (picture == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "图片不存在");
        }
        //删除图片
        ThrowUntil.throwIf(!this.removeById(id), ErrorCode.OPERATION_ERROR, "删除图片失败");
        //删除图片释放对应空间资源
        this.deletePicturePutSpace(picture);
        return true;
    }

    /**
     * 更新图片-管理员
     *
     * @param pictureUpdateRequest
     * @return
     */
    @Override
    public boolean updatePicture(PictureUpdateRequest pictureUpdateRequest,User user) {
        ThrowUntil.throwIf(pictureUpdateRequest == null || pictureUpdateRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureUpdateRequest, picture);
        //标签特殊处理
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        //校验参数
        this.checkPicture(picture);
        //校验权限
        Space space = spaceService.getSpaceById(picture.getSpaceId());
        spaceService.checkSpace(space, user);

        //判断图片是否存在
        Picture picture1 = this.getById(pictureUpdateRequest.getId());
        ThrowUntil.throwIf(picture1 == null, ErrorCode.OPERATION_ERROR, "图片不存在");

        //更新图片
        ThrowUntil.throwIf(!this.updateById(picture), ErrorCode.OPERATION_ERROR, "更新图片失败");
        return true;
    }

    /**
     * 更新图片-用户
     *
     * @param pictureEditRequest
     * @return
     */
    @Override
    public boolean UserupdatePcture(PictureEditRequest pictureEditRequest, User user) {
        //参数校验
        ThrowUntil.throwIf(pictureEditRequest == null || user == null, ErrorCode.PARAMS_ERROR);
        Picture picture = this.getById(pictureEditRequest.getId());
        ThrowUntil.throwIf(picture == null, ErrorCode.OPERATION_ERROR, "图片不存在");

        //判断是否有权限
        ThrowUntil.throwIf(!this.isAdmin(user) && !Objects.equals(user.getId(), picture.getUserId()), ErrorCode.NO_AUTH_ERROR);
        Space space = spaceService.getById(picture.getSpaceId());
        spaceService.checkSpace(space, user);

        BeanUtil.copyProperties(pictureEditRequest, picture);
        //标签特殊处理
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        //校验参数
        this.checkPicture(picture);

        //判断图片是否存在
        Picture picture1 = this.getById(pictureEditRequest.getId());
        ThrowUntil.throwIf(picture1 == null, ErrorCode.OPERATION_ERROR, "图片不存在");
        //添加审核参数
        this.addReviewParams(picture, user);
        //更新图片
        ThrowUntil.throwIf(!this.updateById(picture), ErrorCode.OPERATION_ERROR, "更新图片失败");
        return true;
    }

    /**
     * 校验图片
     *
     * @param picture
     */
    @Override
    public void checkPicture(Picture picture) {
        ThrowUntil.throwIf(picture == null, ErrorCode.PARAMS_ERROR, "图片不存在");
        String name = picture.getName();
        String introduction = picture.getIntroduction();


        if (name != null && name.length() > 20) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "图片名称不能超过20个字符");
        }
        if (introduction != null && introduction.length() > 100) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "图片简介过长");
        }

    }

    /**
     * 补充审核参数
     *
     * @param picture
     * @param user
     */
    @Override
    public void addReviewParams(Picture picture, User user) {
        //如果是管理员，直接通过
        if (this.isAdmin(user)) {
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("管理员自动通过");
            picture.setReviewTime(new Date());
            picture.setReviewerId(user.getId());
        } else {
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }

    }

    /**
     * 审核图片（管理员端）
     *
     * @param pictureReviewRequest
     * @return
     */
    @Override
    public boolean reviewPicture(PictureReviewRequest pictureReviewRequest, User user) {
        //1:校验参数
        if (user == null || pictureReviewRequest == null || pictureReviewRequest.getId() == null || pictureReviewRequest.getReviewStatus() == null) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        //2：查询图片是否存在
        Picture picture = this.getById(pictureReviewRequest.getId());
        if (picture == null) {
            throw new biusnessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        if (picture.getReviewStatus().equals(pictureReviewRequest.getReviewStatus())) {
            throw new biusnessException(ErrorCode.OPERATION_ERROR, "不能重复审核");
        }
        //3：修改图片状态
        picture.setReviewStatus(pictureReviewRequest.getReviewStatus());
        picture.setReviewMessage(pictureReviewRequest.getReviewMessage());
        picture.setReviewTime(new Date());
        picture.setReviewerId(user.getId());
        //4：返回结果
        return this.updateById(picture);
    }

    /**
     * 批量抓取图片
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        String searchText = pictureUploadByBatchRequest.getSearchText();
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (namePrefix == null) {
            namePrefix = searchText;
        }
        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUntil.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new biusnessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new biusnessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }

            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            try {
                //1到5的随机数
                int randomNum1 = RandomUtil.randomInt(0, 4);
                int randomNum2 = RandomUtil.randomInt(0, 8);
                int randomNum3 = RandomUtil.randomInt(0, 8);
                pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
                pictureUploadRequest.setCategory(categoryList.get(randomNum1));
                pictureUploadRequest.setTagList(List.of(tagList.get(randomNum2), tagList.get(randomNum3)));
                PictureVO pictureVO = this.uploadPicture(loginUser, pictureUploadRequest, fileUrl);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;


    }

    /**
     * 删除图片释放对应空间资源
     * @param picture
     */
    @Override
    public void deletePicturePutSpace(Picture picture) {
        //查询图片是否有对应空间
        if (picture.getSpaceId() != null){
            //更新空间图片数量
            Space space = spaceService.getById(picture.getSpaceId());
            ThrowUntil.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            space.setTotalCount(space.getTotalCount() - 1);
            space.setTotalSize(space.getTotalSize() - picture.getPicSize());
            boolean b = spaceService.updateById(space);
            ThrowUntil.throwIf(!b, ErrorCode.OPERATION_ERROR, "空间更新失败");
        }
    }


    /**
     * 以图搜图功能
     *
     * @param spaceId
     * @param picColor
     * @param user
     * @return
     */
    @Override
    public List<PictureVO> searchPictureVoByImage(Long spaceId, String picColor, User user) {
        ThrowUntil.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUntil.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);

        Space space = spaceService.getById(spaceId);
        if (space == null) {
            throw new biusnessException(ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }

        if (!space.getUserId().equals(user.getId())) {
            throw new biusnessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }

        //查询空间所有图片
        List<Picture> pictureList = this.list(new LambdaQueryWrapper<Picture>()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor));

        Color targetColor = Color.decode(picColor);
        //根据空间的图片与所传颜色匹配
        List<Picture> pictures = pictureList.stream().sorted(Comparator.comparing(
                picture -> {
                    String picColor1 = picture.getPicColor();
                    Color color = Color.decode(picColor1);
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, color);
                }
        )).limit(10).toList();


        return pictures.stream().map(PictureVO::objToVo).toList();

    }


    /**
     * 批量编辑
     *
     * @param pictureEditByBatchRequest
     * @param user
     * @return
     */
    @Transactional
    @Override
    public boolean batchEdit(PictureEditByBatchRequest pictureEditByBatchRequest, User user) {
        //校验参数
        this.volatileBatchEditFlag(pictureEditByBatchRequest, user);
        //校验权限
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();

        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUntil.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            ThrowUntil.throwIf(!space.getUserId().equals(user.getId()), ErrorCode.NO_AUTH_ERROR, "无权限");
        }

        //查询图片列表
        List<Picture> pictureList = this.list(new LambdaQueryWrapper<Picture>()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(spaceId != null, Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureEditByBatchRequest.getPictureIdList()));

        if (CollUtil.isEmpty(pictureList)) {
            throw new biusnessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        //批量修改
        pictureList.stream().peek(
                picture -> {
                    if (StrUtil.isNotBlank(category)){
                        picture.setCategory(category);
                    }
                    if (CollUtil.isNotEmpty(tags)){
                        picture.setTags(JSONUtil.toJsonStr( tags));
                    }
                }
        );

        boolean update = this.updateBatchById(pictureList);
        if (!update){
            throw new biusnessException(ErrorCode.OPERATION_ERROR, "图片更新失败");
        }

        return true;
    }

    public void volatileBatchEditFlag(PictureEditByBatchRequest pictureEditByBatchRequest, User user) {
        ThrowUntil.throwIf(pictureEditByBatchRequest.getPictureIdList() == null, ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUntil.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
    }

    /**
     * 批量修改图片（大数据量优化）
     */
//    public boolean batchEditBigData(PictureEditByBatchRequest pictureEditByBatchRequest, User user) {
//        //校验参数
//        this.volatileBatchEditFlag(pictureEditByBatchRequest, user);
//        //校验权限
//        Long spaceId = pictureEditByBatchRequest.getSpaceId();
//        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
//        String category = pictureEditByBatchRequest.getCategory();
//        List<String> tags = pictureEditByBatchRequest.getTags();
//
//        if (spaceId != null) {
//            Space space = spaceService.getById(spaceId);
//            ThrowUntil.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            ThrowUntil.throwIf(!space.getUserId().equals(user.getId()), ErrorCode.NO_AUTH_ERROR, "无权限");
//        }
//
//        //查询图片列表
//        List<Picture> pictureList = this.list(new LambdaQueryWrapper<Picture>()
//                .select(Picture::getId, Picture::getSpaceId)
//                .eq(spaceId != null, Picture::getSpaceId, spaceId)
//                .in(Picture::getId, pictureEditByBatchRequest.getPictureIdList()));
//
//        if (CollUtil.isEmpty(pictureList)) {
//            throw new biusnessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
//        }
//
//        int maxSize=100;
//       List<CompletableFuture<Void>> futures = new ArrayList<>();
//
//        for(int i=0;i<pictureList.size();i+=maxSize){
//           List<Picture> subList = pictureList.subList(i, i + maxSize);
//           CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
//               subList.forEach(
//                       picture -> {
//                           if (StrUtil.isNotBlank(category)){
//                               picture.setCategory(category);
//                           }
//                           if (CollUtil.isNotEmpty(tags)){
//                               picture.setTags(JSONUtil.toJsonStr( tags));
//                           }
//                       }
//               );
//
//               boolean update = this.updateBatchById(subList);
//               if (!update){
//                   throw new biusnessException(ErrorCode.OPERATION_ERROR, "图片更新失败");
//               }
//
//               return null;
//           }, threadPoolExecutor);
//           futures.add(future);
//       }
//        // 等待所有任务完成
//        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
//        return true;
//    }

    /**
     * ai扩图
     */
    @Override
    public ImageEditResponse aiExpand(CreatePictureOutPaintingTaskRequest request) {
        Long pictureId = request.getPictureId();
        Picture picture = this.getPictureById(pictureId);
        if (picture == null){
            throw new biusnessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }

        //创建参数
        ImageEditRequest imageEditRequest = new ImageEditRequest();
        ImageEditRequest.Input input = new ImageEditRequest.Input();
        ImageEditRequest.Parameters parameters = new ImageEditRequest.Parameters();
        input.setImageUrl(picture.getUrl());
        BeanUtil.copyProperties(request.getParameters(), parameters);
        imageEditRequest.setInput(input);
        imageEditRequest.setParameters(parameters);
        return aliImageEditRequestApi.sendRequest(imageEditRequest);
    }


}




